package com.xdh.springcloud.security.jwt.auth.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xdh.springcloud.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationFailureHandler implements org.springframework.security.web.authentication.AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper mapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        Message message = new Message();
        if (e instanceof BadCredentialsException) {
            message.setCode(HttpStatus.UNAUTHORIZED.value());
            message.setMsg("Invalid token");
        } else {
            message.setCode(HttpStatus.UNAUTHORIZED.value());
            message.setMsg(e.getMessage());
        }
        mapper.writeValue(response.getWriter(), message);
    }
}
